package com.cskaoyan.gateway.controller.user;

import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.IloginServices;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/user")

public class LoginController {

    @Reference(timeout = 2000, retries = 0, check = false)
    private IKaptchaService iKaptchaService;//用于验证码判断

    @Reference(timeout = 2000, check = false)
    private IloginServices iloginService;

    @PostMapping("/login")
    @Anoymous//不需要携带token <---> 不需要登录
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request, HttpServletResponse resp){
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");//验证码

        //1验证码验证
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        //调用验证验证码方法得到的返回对象
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        String code = response.getCode();
        if(!code.equals(SysRetCodeConstants.SUCCESS.getCode())){//验证
            return new ResponseUtil<>().setErrorMsg(response.getCode());
        }
        //去表中查数据
        UserLoginRequest loginRequest = new UserLoginRequest();
        loginRequest.setUserName(userName);
        loginRequest.setPassword(userPwd);

        UserLoginResponse loginResponse = iloginService.login(loginRequest);
        if (loginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())) {
            //todo  查出来的loginResponse的对象数据的封装
            Cookie cookie = new Cookie(TokenIntercepter.ACCESS_TOKEN,loginResponse.getToken());
            cookie.setHttpOnly(true);
            cookie.setMaxAge(999999);
            cookie.setPath("/");
            resp.addCookie(cookie);
            return new ResponseUtil<>().setData(loginResponse,"success");
        }
        return new ResponseUtil<>().setErrorMsg(loginResponse.getMsg());
    }
}
